#include <stdio.h>

int read_pmk(const char* filename)
{
	FILE* fp = nullptr;
	fp = fopen(filename, "rb");
	if (!fp) return -1;

	// check id
	char id[2];
	if (fread(id, 1, 2, fp) != 2 || id[0] != 0x13 || id[1] != 0x00) {
		fclose(fp);
		return -1;
	}
	
	// get key frequency
	double key_cycle = 0;
	if (fread(&key_cycle, sizeof key_cycle, 1, fp) != 1) {
		fclose(fp);
		return -1;
	}	
	double keyfreq;
	const double EMPTY_FREQUENCY = 55.0; // empty frequency in frq file is 55.0
	if (key_cycle < 50) {
		keyfreq = EMPTY_FREQUENCY;
	}
	else {
		keyfreq = 44100 / key_cycle;
	}

	// get frequency map
	int datacount = 0;
	if (fread(&datacount, sizeof datacount, 1, fp) != 1 || datacount < 0) {
		fclose(fp);
		return -1;
	}
	
	struct STDFREQ {
		int end;
		int cycle;
	};
	STDFREQ* temp = new STDFREQ[datacount];
	if (fread(temp, sizeof(STDFREQ), datacount, fp) != datacount) {
		fclose(fp);
		delete[] temp;
		return -1;
	}

	// convert pmk to frq format
	int samplelength = temp[datacount - 1].end + temp[datacount - 1].cycle;
	int mapsize = (samplelength + 255) / 256;

	double * freq_table = new double[mapsize];
	int offset = 0;
	int index = 0;
	for (int i = 0; i < mapsize; i++) {
		if (index > datacount - 1) break;
		if (temp[index].cycle < 50) {
			freq_table[i] = EMPTY_FREQUENCY;
		}
		else {
			freq_table[i] = 44100.0 / temp[index].cycle;
		}
		offset += 256;
		while (index < datacount && temp[index].end < offset) {
			index++;
		}
	}
	delete[] temp;

	// keyfreq : key frequency
	// freq_table[] : frequency map
	// mapsize : size of frequency map

	return 0;
}
